Observed log-chlorophyll at representative station in SF Bay Delta region.

library(tidyverse)
library(lubridate)
library(mgcv)  
library(plotly)
library(WRTDStidal)
library(gridExtra)
source('R/funcs.R')

# flow data, left moving window average of 30 days
data(flow_dat)
fl_dat <- flow_dat %>% 
  rename(date = Date) %>% 
  filter(station %in% 'sac') %>% 
  mutate(
    qsm = stats::filter(q, rep(1, 30)/30, sides = 1, method = 'convolution')
  )
  
# format the data to model
data(sf_dat)
sf_mod <- sf_dat %>% 
  filter(Site_Code %in% 'C3') %>% 
  rename(date = Date) %>% 
  mutate(
    doy = yday(date), 
    dec_time = decimal_date(date), 
    yr = year(date),
    mo = month(date, label = T)
  ) %>% 
  left_join(fl_dat, by = 'date') %>% 
  mutate(
    flo = log(qsm), 
    lnchl = log(chl)
    ) %>% 
  select(-q, -qsm, -station, -Latitude, -Longitude, -Location)

# plot, all
p <- ggplot(sf_mod, aes(x = date, y = lnchl)) + 
  geom_line() +
  theme_bw() 
ggplotly(p)
# boxplot, by years
p <- ggplot(sf_mod, aes(x = yr, y = lnchl)) + 
  geom_boxplot() + 
  theme_bw()
ggplotly(p)
# boxplot, by month
p <- ggplot(sf_mod, aes(x = mo, y = lnchl)) + 
  geom_boxplot() + 
  theme_bw()
ggplotly(p)

Some simple GAMs to explore annual, seasonal trends.

# annual only
mod1 <- gam(lnchl ~ s(dec_time, bs = 'tp'),
  data = sf_mod, 
  na.action = na.exclude
  )

# seasonal only
mod2 <- gam(lnchl ~ s(doy, bs = 'cc'), 
  knots = list(doy = c(1, 366)),
  data = sf_mod, 
  na.action = na.exclude
  )
 
# annual and seasonal, additive
mod3 <- gam(lnchl ~ s(dec_time, bs = 'tp') + 
  s(doy, bs = 'cc'), 
  knots = list(doy = c(1, 366)),
  data = sf_mod, 
  na.action = na.exclude
  )

# annual and seasonal, interaction
mod4 <- gam(lnchl ~ te(dec_time, doy, bs = c('tp', 'cc')),
  knots = list(doy = c(1, 366)),
  data = sf_mod, 
  na.action = na.exclude
  )

Summary stats of annual, seasonal models:

mods <- list(
  mod1 = mod1,
  mod2 = mod2, 
  mod3 = mod3,
  mod4 = mod4
  )

# smoother stats of GAMs
map(mods, ~ summary(.x)$s.table %>% data.frame %>% rownames_to_column('smoother')) %>% 
  enframe %>% 
  unnest %>% 
  kable
name smoother edf Ref.df F p.value
mod1 s(dec_time) 6.866894 7.962040 29.95751 0
mod2 s(doy) 3.191626 8.000000 12.60039 0
mod3 s(dec_time) 7.272455 8.281637 35.56688 0
mod3 s(doy) 3.591968 8.000000 18.27905 0
mod4 te(dec_time,doy) 13.362860 15.974582 27.26270 0
# summary stats of GAMs
map(mods, ~ data.frame(
    AIC = AIC(.x), 
    R2 = summary(.x)$r.sq)) %>% 
  enframe %>% 
  unnest %>% 
  kable
name AIC R2
mod1 1117.9219 0.3025777
mod2 1215.8161 0.1606211
mod3 986.8771 0.4548302
mod4 995.0956 0.4490483
# prediction data
pred_dat <- data.frame(
    dec_time = seq(min(sf_mod$dec_time), max(sf_mod$dec_time), length = 1000)
  ) %>% 
  mutate(
    date = date_decimal(dec_time), 
    date = as.Date(date),
    mo = month(date, label = TRUE), 
    doy = yday(date), 
    yr = year(date)
  ) %>% 
  left_join(., fl_dat[, c('date', 'qsm')]) %>% 
  mutate(flo = log(qsm)) %>% 
  select(-qsm)

# predictions
sf_res <- pred_dat %>% 
  mutate(
    mod1 = predict(mod1, newdata = pred_dat), 
    mod2 = predict(mod2, newdata = pred_dat), 
    mod3 = predict(mod3, newdata = pred_dat), 
    mod4 = predict(mod4, newdata = pred_dat)
  ) %>% 
  tidyr::gather('mods', 'pred', -date, -mo, -doy, -dec_time, -yr, -flo)

# plot
p <- ggplot(sf_res, aes(x = date)) + 
  geom_point(data = sf_mod, aes(y = lnchl), size = 0.5) + 
  geom_line(aes(y = pred, colour = mods)) + 
  theme_bw() + 
  theme(
    legend.position = 'top', 
    legend.title = element_blank()
    )
ggplotly(p)
# plot
p <- ggplot(sf_res, aes(x = doy, group = factor(yr), colour = yr)) + 
  geom_line(aes(y = pred)) + 
  theme_bw() + 
  theme(
    legend.position = 'top', 
    legend.title = element_blank()
    ) + 
  facet_wrap(~ mods, ncol = 2)
ggplotly(p)

Adding flow data to the model:

# model, all terms additive
mod5 <- gam(lnchl ~ s(dec_time, bs = 'tp') + s(doy, bs = 'cc') + s(flo, bs = 'tp'),
  knots = list(doy = c(1, 366)),
  data = sf_mod,
  na.action = na.exclude
  )

# model, flo additive, interaction between dec_time, doy
mod6 <- gam(lnchl ~ te(dec_time, doy, bs = c('tp', 'cc')) + s(flo, bs = 'tp'),
  knots = list(doy = c(1, 366)),
  data = sf_mod,
  na.action = na.exclude
  )

# model, doy additive, interaction between dec_time and flow
mod7 <- gam(lnchl ~ te(dec_time, flo, bs = c('tp', 'tp')) + s(doy, bs = 'cc'),
  knots = list(doy = c(1, 366)),
  data = sf_mod,
  na.action = na.exclude
  )

# model, dec_time additive, interaction between flo and doy
mod8 <- gam(lnchl ~ te(flo, doy, bs = c('tp', 'cc')) + s(dec_time, bs = 'tp'),
  knots = list(doy = c(1, 366)),
  data = sf_mod,
  na.action = na.exclude
  )

# model, interaction between flow and doy, interaction between flo and dec_time
mod9 <- gam(lnchl ~ te(flo, doy, bs = c('tp', 'cc')) + te(flo, dec_time, bs = c('tp', 'tp')),
  knots = list(doy = c(1, 366)),
  data = sf_mod,
  na.action = na.exclude
  )

# model, all terms interaction
mod10 <- gam(lnchl ~ te(dec_time, doy, flo, bs = c('tp', 'cc', 'tp')),
  knots = list(doy = c(1, 366)),
  data = sf_mod,
  na.action = na.exclude
  )

Summary stats of annual, seasonal, flow models:

mods2 <- list(
  mod5 = mod5,
  mod6 = mod6, 
  mod7 = mod7,
  mod8 = mod8,
  mod9 = mod9, 
  mod10 = mod10
  )

# smoother stats of GAMs
map(mods2, ~ summary(.x)$s.table %>% data.frame %>% rownames_to_column('smoother')) %>% 
  enframe %>% 
  unnest %>% 
  kable
name smoother edf Ref.df F p.value
mod5 s(dec_time) 7.369642 8.356655 31.480016 0
mod5 s(doy) 3.367204 8.000000 20.930200 0
mod5 s(flo) 7.455219 8.426530 7.472015 0
mod6 te(dec_time,doy) 13.543810 16.196276 26.290240 0
mod6 s(flo) 7.369249 8.366403 7.627124 0
mod7 te(dec_time,flo) 15.242514 18.208885 23.349565 0
mod7 s(doy) 3.668998 8.000000 22.815999 0
mod8 te(flo,doy) 18.256992 18.843439 12.894742 0
mod8 s(dec_time) 7.384604 8.369949 32.857922 0
mod9 te(flo,doy) 13.660332 15.634178 17.353062 0
mod9 te(flo,dec_time) 14.432207 20.000000 16.366477 0
mod10 te(dec_time,doy,flo) 45.650084 57.598811 12.305912 0
# summary stats of GAMs
map(mods2, ~ data.frame(
    AIC = AIC(.x), 
    R2 = summary(.x)$r.sq)) %>% 
  enframe %>% 
  unnest %>% 
  kable
name AIC R2
mod5 934.8386 0.5106123
mod6 941.7425 0.5067670
mod7 912.1389 0.5310632
mod8 941.6199 0.5109185
mod9 925.8831 0.5267709
mod10 896.0992 0.5649017
# predictions
sf_res2 <- pred_dat %>% 
  mutate(
    mod5 = predict(mod5, newdata = pred_dat), 
    mod6 = predict(mod6, newdata = pred_dat), 
    mod7 = predict(mod7, newdata = pred_dat), 
    mod8 = predict(mod8, newdata = pred_dat),
    mod9 = predict(mod9, newdata = pred_dat),
    mod10 = predict(mod10, newdata = pred_dat)
  ) %>% 
  tidyr::gather('mods', 'pred', -date, -mo, -doy, -dec_time, -yr, -flo)

# plot
p <- ggplot(sf_res2, aes(x = date)) + 
  geom_point(data = sf_mod, aes(y = lnchl), size = 0.5) + 
  geom_line(aes(y = pred, colour = mods)) + 
  theme_bw() + 
  theme(
    legend.position = 'top', 
    legend.title = element_blank()
    )
ggplotly(p)
ptheme <- theme(
  axis.title.x = element_blank(), 
  axis.title.y = element_blank()
)
cols <- 'Spectral'
p5 <- dynagam(mod5, pred_dat, ncol = 1, col_vec = cols) + 
  ptheme + 
  theme(legend.position = 'none') +
  ggtitle('mod5')
p6 <- dynagam(mod6, pred_dat, ncol = 1, col_vec = cols) + 
  ptheme + 
  theme(legend.position = 'none') + 
  ggtitle('mod6')
p7 <- dynagam(mod7, pred_dat, ncol = 1, col_vec = cols) + 
  ptheme + 
  theme(legend.position = 'none') + 
  ggtitle('mod7')
p8 <- dynagam(mod8, pred_dat, ncol = 1, col_vec = cols) + 
  ptheme + 
  theme(legend.position = 'none') + 
  ggtitle('mod8')
p9 <- dynagam(mod9, pred_dat, ncol = 1, col_vec = cols) + 
  ptheme + 
  theme(legend.position = 'none') + 
  ggtitle('mod9')
p10 <- dynagam(mod10, pred_dat, ncol = 1, col_vec = cols) + 
  ptheme + 
  ggtitle('mod10')
pleg <- g_legend(p10)
p10 <- p10 + 
  theme(legend.position = 'none')

grid.arrange(
  pleg, 
  arrangeGrob(p5, p6, p7, p8, p9, p10, ncol = 6, bottom = 'lnQ', left = 'lnchl'), 
  ncol = 1, 
  heights = c(0.1, 1)
)

Backwards model selection, see here:

mod <- gam(lnchl ~ s(dec_time, bs = 'tp') + 
              s(doy, bs = 'cc') + 
              s(flo, bs = 'tp') +
              te(flo, doy, bs = c('tp', 'cc')) + 
              te(flo, dec_time, bs = c('tp', 'tp')) +
              te(dec_time, doy, bs = c('tp', 'cc')) +
              te(dec_time, doy, flo, bs = c('tp', 'cc', 'tp')),
            knots = list(doy = c(1, 366)),
            data = sf_mod,
            na.action = na.exclude
)
summary(mod)
## 
## Family: gaussian 
## Link function: identity 
## 
## Formula:
## lnchl ~ s(dec_time, bs = "tp") + s(doy, bs = "cc") + s(flo, bs = "tp") + 
##     te(flo, doy, bs = c("tp", "cc")) + te(flo, dec_time, bs = c("tp", 
##     "tp")) + te(dec_time, doy, bs = c("tp", "cc")) + te(dec_time, 
##     doy, flo, bs = c("tp", "cc", "tp"))
## 
## Parametric coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  0.61252    0.02209   27.73   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Approximate significance of smooth terms:
##                            edf Ref.df     F  p-value    
## s(dec_time)          6.339e+00  7.475 2.969 0.003902 ** 
## s(doy)               1.864e+00  8.000 0.356 0.053668 .  
## s(flo)               6.562e+00  7.697 1.548 0.175616    
## te(flo,doy)          6.260e+00 15.000 1.421 7.89e-05 ***
## te(flo,dec_time)     7.989e+00 16.000 2.972 8.72e-10 ***
## te(dec_time,doy)     7.706e+00 15.000 1.576 0.000341 ***
## te(dec_time,doy,flo) 3.457e-08 48.000 0.000 0.201552    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## R-sq.(adj) =  0.578   Deviance explained = 60.7%
## GCV = 0.28725  Scale est. = 0.26748   n = 548
AIC(mod)
## [1] 870.8656
mod <- gam(lnchl ~ s(dec_time, bs = 'tp') + 
              s(doy, bs = 'cc') + 
              s(flo, bs = 'tp') +
              te(flo, doy, bs = c('tp', 'cc')) + 
              te(flo, dec_time, bs = c('tp', 'tp')) +
              te(dec_time, doy, bs = c('tp', 'cc')),
            knots = list(doy = c(1, 366)),
            data = sf_mod,
            na.action = na.exclude
)
summary(mod)
## 
## Family: gaussian 
## Link function: identity 
## 
## Formula:
## lnchl ~ s(dec_time, bs = "tp") + s(doy, bs = "cc") + s(flo, bs = "tp") + 
##     te(flo, doy, bs = c("tp", "cc")) + te(flo, dec_time, bs = c("tp", 
##     "tp")) + te(dec_time, doy, bs = c("tp", "cc"))
## 
## Parametric coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  0.61252    0.02209   27.73   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Approximate significance of smooth terms:
##                    edf Ref.df     F  p-value    
## s(dec_time)      6.339  7.475 2.969 0.003902 ** 
## s(doy)           1.864  8.000 0.356 0.053668 .  
## s(flo)           6.562  7.697 1.548 0.175616    
## te(flo,doy)      6.260 15.000 1.421 7.89e-05 ***
## te(flo,dec_time) 7.989 16.000 2.972 8.72e-10 ***
## te(dec_time,doy) 7.706 15.000 1.576 0.000341 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## R-sq.(adj) =  0.578   Deviance explained = 60.7%
## GCV = 0.28725  Scale est. = 0.26748   n = 548
AIC(mod)
## [1] 870.8656
mod <- gam(lnchl ~ s(dec_time, bs = 'tp') + 
              s(doy, bs = 'cc') + 
              te(flo, doy, bs = c('tp', 'cc')) + 
              te(flo, dec_time, bs = c('tp', 'tp')) +
              te(dec_time, doy, bs = c('tp', 'cc')),
            knots = list(doy = c(1, 366)),
            data = sf_mod,
            na.action = na.exclude
)
summary(mod)
## 
## Family: gaussian 
## Link function: identity 
## 
## Formula:
## lnchl ~ s(dec_time, bs = "tp") + s(doy, bs = "cc") + te(flo, 
##     doy, bs = c("tp", "cc")) + te(flo, dec_time, bs = c("tp", 
##     "tp")) + te(dec_time, doy, bs = c("tp", "cc"))
## 
## Parametric coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  0.61252    0.02226   27.52   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Approximate significance of smooth terms:
##                     edf Ref.df     F  p-value    
## s(dec_time)       6.428  7.562 4.517 5.08e-05 ***
## s(doy)            3.846  8.000 1.711 6.34e-05 ***
## te(flo,doy)      10.174 12.014 2.876 0.000673 ***
## te(flo,dec_time)  8.206 16.000 3.929 4.44e-13 ***
## te(dec_time,doy)  8.612 12.000 1.789 0.002231 ** 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## R-sq.(adj) =  0.572   Deviance explained = 60.1%
## GCV = 0.29193  Scale est. = 0.27154   n = 548
AIC(mod)
## [1] 879.6259